<template>
  <el-tabs v-model="loginActive" class="demo-tabs" @tab-click="handleClick">

    <el-tab-pane label="手机验证登录" name="first">
      <form class="flex-layout" @submit.prevent="handlePhoneLogin">
        <span>
          <label class="form-label" for="phone-input"></label>
          <el-input
              id="phone-input"
              v-model="phoneNumber"
              class="w-50 m-2"
              placeholder="请输入手机号"
              @input="checkPhoneNumber">
            <template #prefix>
              +86
            </template>
          </el-input>
        </span>
        <span>
          <label class="form-label" for="verification-input"></label>
          <el-input id="verification-input" v-model="verification" class="w-50 m-2" placeholder="验证码">
            <template #suffix>
              <el-button
                  :type="longEnough?'danger':'info'"
                  link
                  @click="sendCode"
                  :disabled="ifSend||!longEnough"
              >
                <span v-if="!ifSend">获取验证码</span>
                <span v-else>{{count}}</span>
              </el-button>

            </template>
          </el-input>
        </span>
        <button type="button" @click="handlePhoneLogin">登录/注册</button>
      </form>
    </el-tab-pane>
    <el-tab-pane label="密码登录" name="second">
      <form class="flex-layout" @submit.prevent="handlePasswordLogin">
        <span>
          <label class="form-label" for="phone-input"></label>
          <el-input
              id="phone-input"
              v-model="phoneNumber"
              class="w-50 m-2"
              placeholder="请输入手机号"
              @input="checkPhoneNumber">
            <template #prefix>
              +86
            </template>
          </el-input>
        </span>
        <span>
          <label class="form-label" for="verification-input"></label>
          <el-input id="verification-input" v-model="password" class="w-50 m-2" placeholder="验证码">
            <template #suffix>
              <el-button
                  type="danger"
                  link
              >
                <span>忘记密码</span>
              </el-button>
            </template>
          </el-input>
        </span>
        <button type="button" @click="handlePasswordLogin">登录</button>
      </form>
    </el-tab-pane>
  </el-tabs>
</template>

<script lang="ts" setup>
import { ref  } from 'vue'
import type { TabsPaneContext } from 'element-plus'
import { ElMessage } from 'element-plus'
import apiService  from '@/axios/index'
const loginActive = ref('first')

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

// 手机验证码登录
let phoneNumber = ref('')
let verification = ref('')
let longEnough = ref(false)
const checkPhoneNumber = (phoneNumber) => {
  longEnough.value = phoneNumber.length === 11;
};

//发送验证码
const sendCode = () => {
  //验证手机号是否正确
  const phoneRegex = /^(0|86|17951)?(13\d|15[0-35-9]|17[0678]|18\d|14[57])\d{8}$/;
  if (!phoneRegex.test(phoneNumber.value)){
    //错误
    ElMessage.error('手机号错误!')
  }else{
    //正确
    sendVerification(phoneNumber.value);
  }
}

//发送验证码请求
interface ApiDataResponse{
  code:number,
  msg:string
}
interface ApiResponse<T> {
  status: number;
  data: ApiDataResponse;
}
let count = ref(0)//定时器倒计时为60秒
let ifSend = ref(false)//发送成功后显示秒数
const sendVerification = async (value: string): Promise<void> => {
  try {
    const response = await apiService
        .post<{ key: string }>('/sendCaptcha', { phoneOrEmail: value }) as ApiResponse<{ key: string }>;
    console.log(response)
    if (response.data.code === 10000) {
      ifSend.value = true;
      count.value=60;
      const timer = setInterval(() => {
        count.value--;
        if (count.value <= 0) {
          // 在组件销毁时清除定时器
          clearInterval(timer);
          ifSend.value = false;
        }
      }, 1000);
      ElMessage.success(response.data.msg);
    } else {
      // 处理其他响应状态，例如显示错误提示
      ElMessage.error(response.data.msg);
    }
  } catch (error) {
    // 处理请求失败的情况，例如显示错误提示
    ElMessage.error('验证码发送失败，请重试！');
  }
};
//整合信息，登录
const handlePhoneLogin = () => {
  const data = {
    captcha:verification.value,
    phone:phoneNumber.value
  };
  loginRequest(data,'/loginByPhoneCaptcha');
}

//账号密码登录
let password=ref('')
const handlePasswordLogin = () => {
  const data = {
    password:verification.value,
    username:phoneNumber.value
  };
  loginRequest(data,'/loginByPhoneCaptcha');
}

const loginRequest = async (data:object,path:string): Promise<void> => {
  try {
    const response = await apiService
        .post<{ key: string }>(path, data) as ApiResponse<{ key: string }>;
    console.log(response)
    if (response.status === 200) {
      ElMessage.success('登录成功！');
    } else {
      // 处理其他响应状态，例如显示错误提示
      ElMessage.error('登录失败！');
    }
  } catch (error) {
    // 处理请求失败的情况，例如显示错误提示
    ElMessage.error('登录失败！');
  }
}
</script>

<style scoped></style>
